#include "unp.h"

void
dg_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen) {
	int			n;
	socklen_t	len;
	char		msg[MAXLINE];

	for ( ; ; ) {
		len = clilen;
		if ((n = recvfrom(sockfd, msg, MAXLINE, 0, pcliaddr, &len)) < 0) {
			perror("recvfrom");
			exit(-1);
		}
		if (sendto(sockfd, msg, n, 0, pcliaddr, len) != n) {
			perror("sendto");
			exit(-1);
		}
	}
}

int
main(int argc, char *argv[]) {
	int					sockfd;
	struct sockaddr_in	servaddr, cliaddr;

	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("creating socket");
		return EXIT_FAILURE;
	}

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);

	if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
		perror("binding");
		return EXIT_FAILURE;
	}

	dg_echo(sockfd, (struct sockaddr *)&cliaddr, sizeof(cliaddr));

	return EXIT_SUCCESS;
}
